package com.example.t1;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class MessengerService extends Service {

    private static final int MSG_SUM = 0x110;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    @SuppressLint("HandlerLeak")
    private Messenger mMessenger = new Messenger(new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            Message msgToClient = Message.obtain(msg);
            switch (msg.what) {
                case MSG_SUM:
                    msgToClient.what = MSG_SUM;
                    try {
                        Thread.sleep(2000);
                        msgToClient.arg2 = msg.arg1 + msg.arg2;
                        msg.replyTo.send(msgToClient);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    });
}
